package com.lswms.modules.lswms.service.impl.statistics;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.lswms.modules.lswms.entity.recipient.RecipientsEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lswms.common.constant.Constant;
import com.lswms.common.page.PageData;
import com.lswms.modules.lswms.dao.statistics.StatisticsDao;
import com.lswms.modules.lswms.entity.stock.InventoryEntity;
import com.lswms.modules.lswms.service.statistics.StatisticsService;

@Service
public class StatisticsServiceImpl implements StatisticsService {

	@Autowired
	StatisticsDao statisticsDao ;
	
	@Override
	public List<Map<String, Object>> getEarlyWarning(Map<String, Object> params) {
		
		String sku = (String)params.get("sku");
		String descr = (String)params.get("descr");

		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq(StringUtils.isNotBlank(sku), "a.sku", sku);
		wrapper.like(StringUtils.isNotBlank(descr), "b.descr", descr);
		wrapper.groupBy("a.sku","b.descr" ,"b.effectlife","b.warningdays") ;
		wrapper.orderByAsc("b.descr");
		
		List<Map<String,Object>> list = statisticsDao.getEarlyWarning(wrapper);
		
		return list;
		
	}

	
	/**
     * 获取分页对象
     * @param params      分页查询参数
     * @param defaultOrderField  默认排序字段
     * @param isAsc              排序方式
     */
    protected IPage<Map<String,Object>> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if(params.get(Constant.PAGE) != null){
            curPage = Long.parseLong((String)params.get(Constant.PAGE));
        }
        if(params.get(Constant.LIMIT) != null){
            limit = Long.parseLong((String)params.get(Constant.LIMIT));
        }

        //分页对象
        Page<Map<String,Object>> page = new Page<>(curPage, limit);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String)params.get(Constant.ORDER_FIELD);
        String order = (String)params.get(Constant.ORDER);

        //前端字段排序
        if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){
            if(Constant.ASC.equalsIgnoreCase(order)) {
                return page.setAsc(orderField);
            }else {
                return page.setDesc(orderField);
            }
        }

        //没有排序字段，则不排序
        if(StringUtils.isEmpty(defaultOrderField)){
            return page;
        }

        //默认排序
        if(isAsc) {
            page.setAsc(defaultOrderField);
        }else {
            page.setDesc(defaultOrderField);
        }

        return page;
    }


	@Override
	public List<Map<String, Object>> getSafetyStock(Map<String, Object> params) {
		String sku = (String)params.get("sku");
		String descr = (String)params.get("descr");

		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq(StringUtils.isNotBlank(sku), "a.sku", sku);
		wrapper.like(StringUtils.isNotBlank(descr), "b.descr", descr);
		wrapper.groupBy(" a.sku,b.descr ,b.safetyqty") ;
		wrapper.having("sum(qty) <= safetyqty", null);
		wrapper.orderByAsc(" descr");
		
		List<Map<String,Object>> list = statisticsDao.getSafetyStock(wrapper);
		
		return list;
	}


	@Override
	public List<Map<String, Object>> getRecipientReport(HttpServletRequest request) throws Exception {
		
		String recipienttime[] = request.getParameterValues("recipienttime");
		String cardid = request.getParameter("cardid");
		String recipientid = request.getParameter("recipientid");
		String recipient = request.getParameter("recipient");
		String sku = request.getParameter("sku");
		String descr = request.getParameter("descr");
		String factorycdoe = request.getParameter("factorycdoe");
		String recipienttype = request.getParameter("recipienttype");
		String sort = request.getParameter("sort");
		

		String[] sorts = null;
		if (StringUtils.isNotBlank(sort)) {
			sorts = sort.split("#");
		}
		if(sorts!=null){
			//当前数组中最后一个（选中的层级中最细的一个）
			sort = sorts.length>0 ? sorts[sorts.length-1] : null;
		}

		
		QueryWrapper<InventoryEntity> wrapper = new QueryWrapper<>();
		wrapper.and(StringUtils.isNotBlank(sku), wrapper1-> wrapper1.eq(StringUtils.isNotBlank(sku), "a.sku", sku).or().eq(StringUtils.isNotBlank(sku), "a.sku", sku) ) ;
		wrapper.like(StringUtils.isNotBlank(descr), "c.descr", descr);
		wrapper.like(StringUtils.isNotBlank(factorycdoe), "c.factorycdoe", factorycdoe);
		wrapper.eq(StringUtils.isNotBlank(cardid), "a.cardid", cardid);
		wrapper.eq(StringUtils.isNotBlank(recipient), "a.recipient", recipient);
		wrapper.eq(StringUtils.isNotBlank(recipientid), "a.recipientid", recipientid);
		wrapper.eq(StringUtils.isNotBlank(recipienttype), "a.recipienttype", recipienttype);
		
		//wrapper.in(sorts != null && sorts.length > 0, "c.sort", sorts);
		wrapper.likeRight(StringUtils.isNotBlank(sort),"c.sort",sort);
		
		if (null != recipienttime && recipienttime.length==2  ) {
			if(StringUtils.isNotBlank(recipienttime[0]) && StringUtils.isNotBlank(recipienttime[1])) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(recipienttime[0].replace('T', ' '));
			Date date2 = sdf.parse(recipienttime[1].replace('T', ' '));

			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(calendar.DATE, 1); // 把日期往后增加一天,整数 往后推,负数往前移动
			date = calendar.getTime();
			
			Calendar calendar2 = new GregorianCalendar();
			calendar2.setTime(date2);
			calendar2.add(calendar2.DATE, 2); // 把日期往后增加两天,整数 往后推,负数往前移动
			date2 = calendar2.getTime();
			wrapper.between("a.recipienttime", date, date2);
			}
		}
		wrapper.isNotNull("a.recipienttime") ;
		wrapper.ge("a.status", "9") ;
		wrapper.groupBy(" a.cardId , d.recipient,d.recipientId,   e.listname , a.sku,c.descr,c.factorycdoe,c.price, convert(nvarchar(7),recipienttime,23),icode.listname") ;
		wrapper.orderByAsc(" a.cardId , d.recipient,d.recipientId, recipienttime,   recipienttype") ;

		List<Map<String,Object>> list = statisticsDao.getRecipientReport(wrapper);
		
		return list;
	}


	@Override
	public List<Map<String,Object>> getRecipientReport2(Map<String,Object> map) throws Exception{


		String recipienttime[] = (String[]) map.get("recipienttime");
		String cardid = (String) map.get("cardid");
		String recipientid = (String)map.get("recipientid");
		String recipient = (String)map.get("recipient");
		String sku = (String)map.get("sku");
		String descr = (String)map.get("descr");
		String factorycdoe =(String) map.get("factorycdoe");
		String recipienttype = (String)map.get("recipienttype");
		String sort =(String) map.get("sort");

		String[] sorts = null;
		if (StringUtils.isNotBlank(sort)) {
			sorts = sort.split("#");
		}
		if(sorts!=null){
			//当前数组中最后一个（选中的层级中最细的一个）
			sort = sorts.length>0 ? sorts[sorts.length-1] : null;
		}


		QueryWrapper<InventoryEntity> wrapper = new QueryWrapper<>();
		wrapper.and(StringUtils.isNotBlank(sku), wrapper1-> wrapper1.eq(StringUtils.isNotBlank(sku), "a.sku", sku).or().eq(StringUtils.isNotBlank(sku), "a.sku", sku) ) ;
		wrapper.like(StringUtils.isNotBlank(descr), "c.descr", descr);
		wrapper.like(StringUtils.isNotBlank(factorycdoe), "c.factorycdoe", factorycdoe);
		wrapper.eq(StringUtils.isNotBlank(cardid), "a.cardid", cardid);
		wrapper.eq(StringUtils.isNotBlank(recipient), "a.recipient", recipient);
		wrapper.eq(StringUtils.isNotBlank(recipientid), "a.recipientid", recipientid);
		wrapper.eq(StringUtils.isNotBlank(recipienttype), "a.recipienttype", recipienttype);

		//wrapper.in(sorts != null && sorts.length > 0, "c.sort", sorts);
		wrapper.likeRight(StringUtils.isNotBlank(sort),"c.sort",sort);

		if (null != recipienttime && recipienttime.length==2  ) {
			if(StringUtils.isNotBlank(recipienttime[0]) && StringUtils.isNotBlank(recipienttime[1])) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdf.parse(recipienttime[0].replace('T', ' '));
				Date date2 = sdf.parse(recipienttime[1].replace('T', ' '));

				Calendar calendar = new GregorianCalendar();
				calendar.setTime(date);
				calendar.add(calendar.DATE, 1); // 把日期往后增加一天,整数 往后推,负数往前移动
				date = calendar.getTime();

				Calendar calendar2 = new GregorianCalendar();
				calendar2.setTime(date2);
				calendar2.add(calendar2.DATE, 2); // 把日期往后增加两天,整数 往后推,负数往前移动
				date2 = calendar2.getTime();
				wrapper.between("a.recipienttime", date, date2);
			}
		}
		wrapper.isNotNull("a.recipienttime") ;
		wrapper.ge("a.status", "9") ;
		wrapper.groupBy(" a.cardId , d.recipient,d.recipientId,   e.listname , a.sku,c.descr,c.factorycdoe,c.price, convert(nvarchar(7),recipienttime,23),icode.listname") ;
		wrapper.orderByAsc(" a.cardId , d.recipient,d.recipientId, recipienttime,   recipienttype") ;

		List<Map<String,Object>> list = statisticsDao.getRecipientReport2(wrapper);
//		System.out.println(list);
		return list;
	}

}
